<template>
	<div>
		<xMd :md="md" />
		<xTabs v-model="editableTabsValue" type="card" editable @edit="handleTabsEdit">
			<xTabPane
				:key="item.name"
				v-for="(item, index) in editableTabs"
				:label="item.title"
				:name="item.name">
				{{ item.content }}
			</xTabPane>
		</xTabs>
	</div>
</template>
<script lang="ts">
export default async function () {
	return defineComponent({
		data() {
			return {
				md: "`editable`属性\n>增减标签页按钮只能在选项卡样式的标签页下使用",
				editableTabsValue: "2",
				editableTabs: [
					{
						title: "Tab 1",
						name: "1",
						content: "Tab 1 content"
					},
					{
						title: "Tab 2",
						name: "2",
						content: "Tab 2 content"
					}
				],
				tabIndex: 2
			};
		},
		methods: {
			handleTabsEdit(targetName, action) {
				if (action === "add") {
					let newTabName = ++this.tabIndex + "";
					this.editableTabs.push({
						title: "New Tab",
						name: newTabName,
						content: "New Tab content"
					});
					this.editableTabsValue = newTabName;
				}
				if (action === "remove") {
					let tabs = this.editableTabs;
					let activeName = this.editableTabsValue;
					if (activeName === targetName) {
						tabs.forEach((tab, index) => {
							if (tab.name === targetName) {
								let nextTab = tabs[index + 1] || tabs[index - 1];
								if (nextTab) {
									activeName = nextTab.name;
								}
							}
						});
					}

					this.editableTabsValue = activeName;
					this.editableTabs = tabs.filter(tab => tab.name !== targetName);
				}
			}
		}
	});
}
</script>
<style lang="less"></style>
